package com.ce.cetag.util;

/**
 *
 * @author <a href="mailto:shaibiao@yahoo.com.cn">��˧��贺帅彪</a>
 *  create on: 2007-7-18
 */
public class UiString {

	public static String simpleConstruct(String template, String[] params) {
		int currIndex = 0;
		int openIndex = 0;
		int closeIndex = 0;
		int listIndex = 0;
		StringBuffer result = new StringBuffer();
		boolean loop = true;

		while (true) {
			openIndex = template.indexOf("{", currIndex);
			if (openIndex < 0) {
				loop = false;
			} else {
				closeIndex = template.indexOf("}", openIndex);
				if (closeIndex < 0) {
					loop = false;
				}
			}
			if (!loop) {
				result.append(template.substring(currIndex, template.length()));
				break;
			}
			result.append(template.substring(currIndex, openIndex));
			try {

				listIndex = Integer.parseInt(template.substring(openIndex + 1,
						closeIndex));
				if (listIndex < 0) {
					throw new NumberFormatException(
							"Invalid parameter position index '" + listIndex
									+ "'.");
				}
				if (listIndex >= params.length) {
					String holder = "{" + listIndex + "}";
					result.append(holder);
					currIndex = openIndex + holder.length();
				} else {
					result.append(String.valueOf(params[listIndex]));
					currIndex = closeIndex + 1;
				}
			} catch (NumberFormatException x) {
				result.append("{");
				currIndex = openIndex + 1;
			}
		}
		return result.toString();
	}

	public static String escapeJs(String str) {
		return escapeJava(str);
	}

	public static String escapeJava(String str) {
		StringBuffer buffer = new StringBuffer();
		char curr;
		for (int i = 0; i < str.length(); i++) {
			curr = str.charAt(i);
			switch (curr) {
			case '\'':
				buffer.append("\\\'");
				break;
			case '"':
				buffer.append("\\\"");
				break;
			case '\\':
				buffer.append("\\\\");
				break;
			default:
				buffer.append(curr);
			}
		}
		return String.valueOf(buffer);
	}

	public static String encodeHtml(String str) {
		StringBuffer buffer = new StringBuffer();
		char curr;
		for (int i = 0; i < str.length(); i++) {
			curr = str.charAt(i);
			switch (curr) {
			case '<':
				buffer.append("&lt;");
				break;
			case '>':
				buffer.append("&gt;");
				break;
			case '&':
				buffer.append("&amp;");
				break;
			case ' ':
				buffer.append("&nbsp;");
				break;
			case '"':
				buffer.append("&quot;");
				break;
			case '\'':
				buffer.append("&#039;");
				break;
			default:
				buffer.append(curr);
			}
		}
		return String.valueOf(buffer);
	}

}
